/*
 *
 *  * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 *
 *
 */

package com.iwindplus.binlog.comsumer.server.strategy.context;

import com.iwindplus.base.domain.enums.DbActionTypeEnum;
import com.iwindplus.base.domain.exception.BizException;
import com.iwindplus.binlog.comsumer.server.domain.dto.BinlogActionProcessDTO;
import com.iwindplus.binlog.comsumer.server.domain.enums.BinlogConsumerCodeEnum;
import com.iwindplus.binlog.comsumer.server.strategy.BinlogActionStrategy;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.stereotype.Component;

/**
 * binlog 操作策略上下文.
 *
 * @param <T> 参数
 * @param <R> 结果
 * @author zengdegui
 * @since 2025/11/29 23:50
 */
@Component
public class BinlogActionStrategyContext<T, R> {

    private final Map<DbActionTypeEnum, BinlogActionStrategy<T, R>> strategyMap;

    /**
     * 构造函数.
     *
     * @param strategies 策略列表
     */
    public BinlogActionStrategyContext(List<BinlogActionStrategy<T, R>> strategies) {
        strategyMap = strategies.stream()
            .collect(Collectors.toMap(BinlogActionStrategy::support, Function.identity()));
    }

    /**
     * 执行业务逻辑.
     *
     * @param entity 对象
     */
    public R execute(BinlogActionProcessDTO<T> entity) {
        BinlogActionStrategy<T, R> strategy = strategyMap.get(entity.getActionType());
        if (strategy == null) {
            throw new BizException(BinlogConsumerCodeEnum.INVALID_ACTION_STRATEGY);
        }

        return strategy.execute(entity);
    }
}
